package web

import (
	"AQChain/models"
	"AQChain/p2p"
	"AQChain/web/impl"
	"github.com/astaxie/beego"
	"github.com/gorilla/websocket"
	"github.com/pkg/browser"
	"github.com/spf13/viper"
	"log"
	"net/http"
	"sync"
)

// web 负责管理了与web端交互
type Web struct {
	Address    string
	WebAddress string

	account models.Account
	p2pnet  p2p.P2P

	// 连接
	wsConn *websocket.Conn
	conn   *impl.Connection
	//转换器
	upGrader websocket.Upgrader
	// 锁 在一个页面打开websocket时锁定
	wsLock sync.Mutex
}

// 初始化Web
func NewWeb(p p2p.P2P, a models.Account) (web Web) {
	web = Web{
		Address:    viper.GetString("config.address"),
		WebAddress: viper.GetString("config.webAddress"),
		account:    a,
		p2pnet:     p,
		wsLock:     sync.Mutex{},
		upGrader: websocket.Upgrader{
			CheckOrigin: func(r *http.Request) bool { //允许跨域
				return true
			},
		},
	}
	return
}

func (web Web) Start() {

	go func() {
		//HandleFunc 的第一个参数指的是请求路径，第二个参数是一个函数类型，表示这个请求需要处理的事情。
		http.HandleFunc("/ws/set", web.WSHandler) //配置路由,ws代表websocket

		http.HandleFunc("/http/account/myAccount", web.AccountMyAccountHandler)
		http.HandleFunc("/http/blockChain/block", web.BlockChainBlockHandler)
		http.HandleFunc("/http/blockChain/myBlock", web.BlockChainMyBlockHandler)
		http.HandleFunc("/http/blockChain/transaction", web.BlockChainTransactionHandler)
		http.HandleFunc("/http/file/upload", web.FileUploadHandler)
		http.HandleFunc("/http/file/list", web.FileListHandler)
		http.HandleFunc("/http/file/myFile", web.FileMyFileHandler)
		http.HandleFunc("/http/file/create", web.TransferOfferHandler)
		http.HandleFunc("/http/transfer/offerList", web.TransferOfferListHandler)
		http.HandleFunc("/http/transfer/modifyList", web.TransferModifyListHandler)
		http.HandleFunc("/http/transfer/confirmList", web.TransferConfirmListHandler)
		http.HandleFunc("/http/transfer/completeList", web.TransferCompleteListHandler)
		http.HandleFunc("/http/transfer/active", web.TransferActiveHandler)
		http.HandleFunc("/http/transfer/offer", web.TransferOfferHandler)
		http.HandleFunc("/http/transfer/confirm", web.TransferConfirmHandler)
		http.HandleFunc("/http/transfer/complete", web.TransferCompleteHandler)
		http.HandleFunc("/http/transfer/cancel", web.TransferCancelHandler)
		http.HandleFunc("/http/transfer/terminate", web.TransferTerminateHandler)

		log.Println("AQChain client address :" + web.Address)
		//第一个参数是监听的端口、第二个参数是根页面的处理函数，可以为空。
		err := http.ListenAndServe(web.Address, nil)
		if err != nil {
			log.Println(err)
		}
	}()

	go beego.Run(web.WebAddress)

	//browser.OpenURL("http://" + "127.0.0.1:8080" + "/static/views/index.html")
	browser.OpenURL("http://" + web.WebAddress + "/index")
}
